<template>
  <div
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <lb-layout>
      <aps-form
        :config="apsForm3.formConfig"
        :model="apsForm3.formData"
        :formRef="apsForm3.formRef"
        :labelWidth="apsForm3.labelWidth"
        ref="form3"
        style="width: 1000px; margin: 0 auto"
      ></aps-form>
      <aps-form
        :config="apsForm.formConfig"
        :model="apsForm.formData"
        :formRef="apsForm.formRef"
        :labelWidth="apsForm.labelWidth"
        ref="form"
        class="mt20"
      ></aps-form>
      <lb-table
        :column="tableData.column"
        :data="tableData.data"
        pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 30, 40]"
        :pager-count="5"
        :current-page.sync="currentPage"
        height="390"
        :total="total"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @p-current-change="handleCurrentChange"
      >
      </lb-table>

      <audit-detail :id="id" :visible.sync="show" @close="close"></audit-detail>
    </lb-layout>
  </div>
</template>

<script>
import { getnetworks } from "@/api/system/dept";
import CascaderSelect from "@/components/Select/CascaderSelect";
import { list, add } from "@/api/iot/remoteDebugging";
import { replaceInteger, isUrl } from "@/utils/index";
import auditDetail from "@/views/work/components/auditDetail.vue";
import auth from "@/plugins/auth";

export default {
  name: "remoteDebugging",
  dicts: ["device_model", "set_status"],
  components: {
    auditDetail,
  },
  data() {
    return {
      id: "",
      show: true,
      apsForm3: {
        formRef: "form3",
        labelWidth: "200px",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            size: "small",
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              uploadInterval: [
                {
                  required: false,
                  message: "定时上传间隔",
                  trigger: "blur",
                },
              ],
              alarmPower: [
                {
                  required: false,
                  message: "请输入预警功率",
                  trigger: "blur",
                },
              ],
              ip: [
                {
                  required: false,
                  validator: this.validatorUrl,
                  trigger: ["blur", "change"],
                },
              ],
              port: [
                {
                  required: false,
                  message: "请输入远程连接端口",
                  trigger: "blur",
                },
              ],
              newDeviceCode: [
                {
                  required: false,
                  message: "请输入设备编号",
                  trigger: "blur",
                },
              ],
            },
          },

          properties: {
            //这里是渲染查询表单的表头和类型的数据
            uploadInterval: {
              label: "定时上传间隔（分钟）",
              typeName: "el-input",
              input: (value) => this.setVal(value, "uploadInterval"),
            },
            alarmPower: {
              label: "预警功率（w）",
              typeName: "el-input",
            },
            ip: {
              label: "远程连接IP",
              typeName: "el-input",
              input: (value) => this.setVal(value, "ip"),
            },
            port: {
              label: "远程连接端口",
              typeName: "el-input",
              input: (value) => this.setVal(value, "port"),
            },
            newDeviceCode: {
              label: "设备编号",
              typeName: "el-input",
            },
          },
          formSoltButton: [
            {
              label: "提交审核",
              type: "primary",
              typeName: "el-button",
              size: "small",
              display: true,
              icon: "el-icon-check",
              click: this.handleSubmit,
            },
            {
              label: "重置",
              typeName: "el-button",
              plain: true,
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.resetForm,
            },
          ],
        },
      },
      multipleSelection: [],
      networkOptions: [],
      show: false,
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            deviceCode: {
              label: "设备编号或名称:",
              typeName: "el-input",
              placeholder: "请输入设备编号或名称",
            },
            sysDeptId: {
              label: "所属用能单位:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      values={that.$refs?.form?.getFieldsValue().sysDeptId}
                      value={that.$refs?.form?.getFieldsValue().sysDeptId}
                      varient={"energy"}
                      placeholder={"请选择所属用能单位"}
                      onInput={that.getNetworkList}
                      clearable={false}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            monitoringNetworkId: {
              label: "所属能耗终端:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().monitoringNetworkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择所属能耗终端",
                        value: valNum,
                        disabled: !that.$refs?.form?.getFieldsValue().sysDeptId,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "monitoringNetworkId",
                            value
                          );
                        },
                      },
                    },
                    [
                      that.networkOptions.map((item) => {
                        let { id, name } = item;
                        return h("el-option", {
                          props: {
                            label: name,
                            value: id,
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            // {
            //   label: "批量审批",
            //   typeName: "el-button",
            //   size: "small",
            //   icon: "el-icon-s-check",
            //   type: "warning",
            //   disabled: true,
            //   click: () => this.handleApproval(1),
            // },
          ],
        },
      },
      tableData: {
        column: [
          {
            type: "selection",
            width: 60,
            align: "center",
            // selectable: this.selectable,
          },
          {
            prop: "deptName",
            label: "用能单位",
            showOverflowTooltip: true,
            minWidth: 100,
          },
          {
            prop: "networkName",
            label: "能耗终端",
            minWidth: 100,
            showOverflowTooltip: true,
          },
          {
            prop: "deviceCode",
            label: "设备编码",
            minWidth: 150,
            showOverflowTooltip: true,
          },
          {
            prop: "name",
            label: "设备名称",
            minWidth: 100,
            showOverflowTooltip: true,
          },
          {
            prop: "model",
            label: "设备型号",
            minWidth: 120,
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.device_model}
                    value={scope.row.model}
                  />
                </div>
              );
            },
          },
          {
            prop: "uploadInterval",
            label: "定时上传间隔（分钟）",
            minWidth: 180,
          },
          {
            prop: "alarmPower",
            label: "预警功率（W）",
            width: 140,
          },
          {
            prop: "status",
            label: "状态",
            width: 150,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.set_status}
                    value={scope.row.status}
                  />
                </div>
              );
            },
          },
          {
            prop: "hardVersion",
            label: "参数件版本号",
            minWidth: 100,
            showOverflowTooltip: true,
          },
          {
            prop: "lastUpdateTime",
            label: "参数最新升级时间",
            width: 180,
          },

          {
            label: "操作",
            width: "100",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a;
              let b;
              if (scope.row.status === 81 || scope.row.status === 82) {
                a = (
                  <el-button
                    v-hasPermi={["plug:update:audit"]}
                    type="text"
                    size="small"
                    icon="el-icon-edit-outline"
                    onClick={() => {
                      that.handleApproval(scope.row);
                    }}
                  >
                    审核
                  </el-button>
                );
              } else {
                a = <div style="display:none"></div>;
              }
              if (scope.row.status === 80) {
                b = (
                  <el-button
                    v-hasPermi={["plug:update:audit"]}
                    type="text"
                    icon="el-icon-setting"
                    size="small"
                    onClick={() => {
                      that.handleApproval(scope.row);
                    }}
                  >
                    下发
                  </el-button>
                );
              } else {
                b = <div style="display:none"></div>;
              }
              return (
                <div>
                  {a}
                  {b}
                </div>
              );
            },
          },
        ],
        data: [],
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
    };
  },
  mounted() {
    this.judgePermi();
    this.getNetwork();
    this.initData();
  },
  methods: {
    judgePermi() {
      if (auth.hasPermi("plug:set:add")) {
        this.apsForm3.formConfig.formSoltButton[0].display = false;
      }
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
    // selectable(row, index) {
    //   if (row.id && [81, 82].includes(row.status)) {
    //     return true; //不可勾选
    //   } else {
    //     return false; //可勾选
    //   }
    // },
    validatorUrl(rules, value, callback) {
      if (value) {
        if (!isUrl(value)) {
          callback("请输入正确的IP地址");
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    handleSubmit() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning("请勾选至少一条设备");
        return false;
      }
      this.$refs.form3.validate((valid) => {
        if (valid) {
          const data = {
            ...this.$refs.form3.getFieldsValue(),
            plugSetInfoBoList: this.multipleSelection,
          };
          add(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.handlerSearchDetail();
            })
            .catch(() => {
              // this.$message.error("系统错误,请联系管理员!300905");
            });
        } else {
          return false;
        }
      });
    },
    setVal(val, key) {
      if (key == "uploadInterval" || key == "port") {
        this.$refs?.form3?.setFieldValue(key, replaceInteger(val));
      } else {
        this.$refs?.form3?.setFieldValue(key, val);
      }
      if (
        this.$refs?.form3?.getFieldsValue().ip ||
        this.$refs?.form3?.getFieldsValue().port
      ) {
        this.apsForm3.formConfig.formAttr.rules.ip[0].required = true;
        this.apsForm3.formConfig.formAttr.rules.port[0].required = true;
      } else {
        this.apsForm3.formConfig.formAttr.rules.ip[0].required = false;
        this.apsForm3.formConfig.formAttr.rules.port[0].required = false;
      }
    },
    //审批 驳回 下发
    handleApproval(row) {
      this.id = row.id || "";
      this.show = true;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getNetwork() {
      getnetworks({
        sysDeptId: this.$refs?.form?.getFieldsValue().sysDeptId,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.networkOptions = res.rows;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20001");
        });
    },
    getNetworkList(data) {
      let result;
      if (data && data.length > 0) {
        result = data[data.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("sysDeptId", result);
      this.$refs?.form?.setFieldValue("monitoringNetworkId", "");
      // this.getNetwork();
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      this.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300901");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      this.initData(currentPage, this.pageSize, data);
    },

    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    resetForm() {
      this.$refs?.form3?.resetFields();
    },
  },
};
</script>
